import router from './router'
import store from './store'
import {
	Message
} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
NProgress.configure({
	easing: 'ease', // 动画方式
	speed: 500, // 递增进度条的速度
	showSpinner: false, // 是否显示加载ico
	trickleSpeed: 200, // 自动递增间隔
	minimum: 0.3, // 初始化时的最小百分比
})

const whiteList = ['/Login', '/Register'] //当前路由不需要验证token

router.beforeEach(async (to, from, next) => {
	// start progress bar
	NProgress.start()
	//获取用户token
	const hasToken = localStorage.getItem('token')

	if (hasToken) {
		if (to.path === '/Login') {
			// if is logged in, redirect to the home page
			next({
				path: '/'
			})
			NProgress.done()
		} else {
			const hasGetUserInfo = store.getters.userInfo //当前用户
			const hasRoles = store.getters.routes && store.getters.routes.length > 0
			if (hasGetUserInfo) {
				if(hasRoles){//判断有没有路由权限
					next()
				}else{
					try {
						//获取后台权限路由
						const routes = await store.dispatch('user/getInfo')
						//对比前端路由返回需要的权限路由
						const accessRoutes = await store.dispatch('permission/generateRoutes', routes)
						router.addRoutes(accessRoutes)
						next({ ...to, replace: true })
					} catch (error) {
					}
				}
				
				
			} else {
				// 获取用户信息失败
				await store.dispatch('user/resetToken')
				Message.error('获取用户信息失败')
				next(`/Login`)
			}
		}
	} else {
		//当前用户没有token
		console.log(to.path);
		if (whiteList.indexOf(to.path) !== -1) {
			// in the free login whitelist, go directly
			next()
		} else {
			// other pages that do not have permission to access are redirected to the login page.
			next(`/Login`)
			NProgress.done()
		}
	}
})

router.afterEach(() => {
	// finish progress bar
	NProgress.done()
})
